πŸ‘©β€πŸ’» 17684. μ••μΆ•

@Seongukbaek Posted May 25, 2022 Β· Updated May 25, 2022 Β· 3 min read

문제

Programmers - μ••μΆ•

πŸ“ Logic

private int findWord(String[] msg, int i) { StringBuilder w = new StringBuilder(msg[i]); int idx = -1; // 사전에 ν¬ν•¨λ˜μ§€ μ•ŠλŠ” 단어λ₯Ό 찾을 λ•ŒκΉŒμ§€ 문자λ₯Ό 계속 λΆ™μž„ while (dic.containsKey(w.toString())) { idx = dic.get(w.toString()); i++; if (i == msg.length) break; w.append(msg[i]); } // 뢙인 단어λ₯Ό 사전에 μΆ”κ°€ν•˜κ³ , 이미 찾은 색인을 배열에 μΆ”κ°€ dic.put(w.toString(), max++); index.add(idx); // i++ 된 μ΄ν›„λ‘œ λ°˜λ³΅λ¬Έμ„ λ‚˜μ˜€κΈ° λ•Œλ¬Έμ— -1ν•œ 값을 λ°˜ν™˜ return i - 1; }
  • 사전에 ν¬ν•¨λ˜μ§€ μ•Šμ€ 단어λ₯Ό 찾을 λ•ŒκΉŒμ§€, 색인을 계속 μ—…λ°μ΄νŠΈν•˜λ©΄μ„œ 문자λ₯Ό 뢙인닀.
  • 반볡문이 μ’…λ£Œλ˜μ—ˆμ„ λ•ŒλŠ”,

    • 사전에 ν¬ν•¨λœ κ°€μž₯ κΈ΄ λ‹¨μ–΄μ˜ 색인과,
    • 사전에 ν¬ν•¨λ˜μ§€ μ•Šμ€ κ°€μž₯ κΈ΄ 단어λ₯Ό ꡬ할 수 μžˆλ‹€.

πŸ“„ CODE

μ½”λ“œ 보기/μ ‘κΈ°πŸ’«
import java.util.*; class Dic { Map<String, Integer> dic; ArrayList<Integer> index; int max = 27; String[] alpha = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}; public Dic() { dic = new HashMap<>(); index = new ArrayList<>(); initDic(); } // 사전 μ΄ˆκΈ°ν™” private void initDic() { for (int i = 0; i < 26; i++) dic.put(alpha[i], i + 1); } public int[] compress(String[] msg) { for (int i = 0; i < msg.length; i++) i = findWord(msg, i); return index.stream().mapToInt(i -> i).toArray(); } // iλ²ˆμ§ΈλΆ€ν„° 사전에 ν¬ν•¨λ˜μ§€ μ•Šμ€ 단어λ₯Ό μ°ΎλŠ”λ‹€. private int findWord(String[] msg, int i) { StringBuilder w = new StringBuilder(msg[i]); int idx = -1; // 사전에 ν¬ν•¨λ˜μ§€ μ•ŠλŠ” 단어λ₯Ό 찾을 λ•ŒκΉŒμ§€ 문자λ₯Ό 계속 λΆ™μž„ while (dic.containsKey(w.toString())) { idx = dic.get(w.toString()); i++; if (i == msg.length) break; w.append(msg[i]); } // 뢙인 단어λ₯Ό 사전에 μΆ”κ°€ν•˜κ³ , 이미 찾은 색인을 배열에 μΆ”κ°€ dic.put(w.toString(), max++); index.add(idx); // i++ 된 μ΄ν›„λ‘œ λ°˜λ³΅λ¬Έμ„ λ‚˜μ˜€κΈ° λ•Œλ¬Έμ— -1ν•œ 값을 λ°˜ν™˜ return i - 1; } } class Solution { public int[] solution(String msg) { Dic d = new Dic(); return d.compress(msg.split("")); } }

✏️ Review

  • μ‚¬μ „μ΄λΌλŠ” 단어λ₯Ό λ³΄μ•˜μ„ λ•Œ λ°”λ‘œ Map 을 μ‚¬μš©ν•΄μ•Όκ² λ‹€κ³  μƒκ°ν–ˆλ‹€.
  • μ‰¬μš΄ 문제..
@Seongukbaek
배우고 μ •λ¦¬ν•˜κ³  κ³΅μœ ν•˜λŠ” λŒ€ν•™μƒ λ°±μ„±μš±μž…λ‹ˆλ‹€ πŸ˜€